package org.learn.phase3.upload;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPFileUploadServer {
    public static void main(String[] args) throws Exception {
        //1.在本机的8888端口监听，等待连接
        //要求8888没有被占用
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("服务器在8888端口监听、、、、");
        //等候连接
        Socket socket = serverSocket.accept();

        //3.读取客户端发送的数据
        //通过Socket 得到输入流
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = streamToByteArray(bis);
        //4.将得到 bytes 数组，写入到指定的路径，就可以得到一个文件了
        String destFilePath = "src\\dog.jpg";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
        bos.write(bytes);
        bos.close();

        //向客户端回复“收到图片”
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write("Client,我已经收到图片");
        writer.flush();//刷新
        socket.shutdownOutput();//写入结束标记

        //关闭流
        writer.close();
        bis.close();
        socket.close();
        serverSocket.close();
    }
    //方法
    public static byte[] streamToByteArray(InputStream is) throws Exception{
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len ;
        while ((len = is.read(b)) != -1){
            bos.write(b,0,len);
        }
        byte[] array = bos.toByteArray();
        bos.close();
        return array;
    }
}
